<template>
  <div class="tetris-container">
    <!-- 修改游戏菜单样式 -->
    <div v-if="showGameMenu" class="game-menu">
      <div class="menu-content">
        <h2>街机游戏厅</h2>
        <div class="game-list">
          <div class="game-item" @click="selectGame('tetris')">
            <div class="game-icon">🎮</div>
            <div class="game-name">俄罗斯方块</div>
            <div class="game-desc">经典街机游戏</div>
          </div>
          <div class="game-item" @click="selectGame('rpg')">
            <div class="game-icon">⚔️</div>
            <div class="game-name">RPG冒险</div>
            <div class="game-desc">即将推出</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 优化游戏界面布局 -->
    <div v-if="!showGameMenu && currentGame === 'tetris'" class="game-content">
      <div class="game-header">
        <div class="score-board">
          <div class="score">
            <span class="label">分数</span>
            <span class="value">{{ score }}</span>
          </div>
          <div class="level">
            <span class="label">等级</span>
            <span class="value">{{ level }}</span>
          </div>
        </div>
        <div class="controls">
          <button class="control-btn primary" @click="toggleGame">
            {{ isPlaying ? '暂停' : '开始' }} (P)
          </button>
          <button class="control-btn" @click="resetGame">
            重置 (R)
          </button>
          <button class="control-btn" @click="$router.push('/')">返回</button>
        </div>
        <div class="key-hints">
          <span>方向键：移动/旋转</span>
          <span>P：暂停/开始</span>
          <span>R：重置游戏</span>
        </div>
      </div>

      <div class="game-area">
        <div class="game-main">
          <canvas ref="gameCanvas" :width="320" :height="640"></canvas>
        </div>
        <div class="game-sidebar">
          <div class="next-piece">
            <h3>下一个方块</h3>
            <canvas ref="nextCanvas" :width="100" :height="100"></canvas>
          </div>
        </div>
      </div>

      <div class="mobile-controls" v-if="isMobile">
        <button @click="moveLeft"><i class="fas fa-arrow-left"></i></button>
        <button @click="moveDown"><i class="fas fa-arrow-down"></i></button>
        <button @click="moveRight"><i class="fas fa-arrow-right"></i></button>
        <button @click="rotate"><i class="fas fa-redo"></i></button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const gameCanvas = ref(null)
const nextCanvas = ref(null)
const score = ref(0)
const level = ref(1)
const isPlaying = ref(false)
const isMobile = ref(false)
const showGameMenu = ref(true)
const currentGame = ref('')

// 游戏核心变量
let ctx
let nextCtx
let gameLoop
let currentPiece = null
let nextPiece = null
let board = Array(20).fill().map(() => Array(10).fill(0))

// 方块形状定义
const PIECES = [
  [[1, 1, 1, 1]], // I
  [[1, 1], [1, 1]], // O
  [[1, 1, 1], [0, 1, 0]], // T
  [[1, 1, 1], [1, 0, 0]], // L
  [[1, 1, 1], [0, 0, 1]], // J
  [[1, 1, 0], [0, 1, 1]], // S
  [[0, 1, 1], [1, 1, 0]]  // Z
]

// 颜色定义
const COLORS = [
  '#FF0D72', '#0DC2FF', '#0DFF72',
  '#F538FF', '#FF8E0D', '#FFE138', '#3877FF'
]

// 添加游戏配置常量
const GAME_CONFIG = {
  BASE_SPEED: 60,  // 基础刷新率 (fps)
  DROP_SPEED: 2,   // 正常下落速度 (每秒格数)
  FAST_DROP_SPEED: 20, // 快速下落速度
  RENDER_DELAY: 1000 / 60  // 渲染间隔 (60fps)
}

let lastDropTime = 0
let lastRenderTime = 0
let animationFrame = null

// 粒子系统
class Particle {
  constructor(x, y, color) {
    this.x = x
    this.y = y
    this.color = color
    this.size = Math.random() * 3 + 2
    this.speedX = Math.random() * 6 - 3
    this.speedY = Math.random() * -6 - 2
    this.gravity = 0.1
    this.life = 1
    this.decay = Math.random() * 0.02 + 0.02
  }

  update() {
    this.speedY += this.gravity
    this.x += this.speedX
    this.y += this.speedY
    this.life -= this.decay
  }

  draw(ctx) {
    ctx.globalAlpha = this.life
    ctx.fillStyle = this.color
    ctx.fillRect(this.x, this.y, this.size, this.size)
    ctx.globalAlpha = 1
  }
}

let particles = []

const createParticles = (x, y, color) => {
  for (let i = 0; i < 15; i++) {
    particles.push(new Particle(x, y, color))
  }
}

const updateParticles = () => {
  particles = particles.filter(p => p.life > 0)
  particles.forEach(p => p.update())
}

const drawParticles = () => {
  particles.forEach(p => p.draw(ctx))
}

const init = () => {
  // 只有当选择了俄罗斯方块游戏时才初始化画布
  if (currentGame.value === 'tetris') {
    // 添加延时确保 DOM 已经渲染
    nextTick(() => {
      ctx = gameCanvas.value.getContext('2d')
      nextCtx = nextCanvas.value.getContext('2d')
      
      // 检测是否为移动设备
      isMobile.value = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
      
      // 初始化游戏
      resetGame()
      
      // 键盘事件监听
      window.addEventListener('keydown', handleKeyPress)
    })
  }
}

const resetGame = () => {
  board = Array(20).fill().map(() => Array(10).fill(0))
  score.value = 0
  level.value = 1
  currentPiece = createNewPiece()
  nextPiece = createNewPiece()
  cancelAnimationFrame(gameLoop)
  draw()
}

const createNewPiece = () => {
  const pieceIndex = Math.floor(Math.random() * PIECES.length)
  return {
    shape: JSON.parse(JSON.stringify(PIECES[pieceIndex])), // 深拷贝形状数组
    color: COLORS[pieceIndex],
    x: 3,
    y: 0
  }
}

const toggleGame = () => {
  if (!currentPiece) {
    resetGame()
  }
  isPlaying.value = !isPlaying.value
  if (isPlaying.value) {
    lastDropTime = performance.now()
    lastRenderTime = performance.now()
    gameLoop = requestAnimationFrame(update)
  } else {
    cancelAnimationFrame(gameLoop)
  }
}

const update = (timestamp) => {
  if (!isPlaying.value) return

  // 处理下落逻辑
  const dropDelay = 1000 / (GAME_CONFIG.DROP_SPEED * level.value)
  if (timestamp - lastDropTime >= dropDelay) {
    moveDown()
    lastDropTime = timestamp
  }

  // 处理渲染逻辑
  if (timestamp - lastRenderTime >= GAME_CONFIG.RENDER_DELAY) {
    draw()
    lastRenderTime = timestamp
  }

  gameLoop = requestAnimationFrame(update)
}

const draw = () => {
  ctx.clearRect(0, 0, gameCanvas.value.width, gameCanvas.value.height)
  drawBoard()
  drawGhostPiece()
  drawCurrentPiece()
  
  // 更新和绘制粒子
  updateParticles()
  drawParticles()
  
  nextCtx.clearRect(0, 0, nextCanvas.value.width, nextCanvas.value.height)
  drawNextPiece()
}

const drawBoard = () => {
  board.forEach((row, y) => {
    row.forEach((value, x) => {
      if (value) {
        ctx.fillStyle = COLORS[value - 1]
        ctx.fillRect(x * 32, y * 32, 31, 31)
      }
    })
  })
}

const drawGhostPiece = () => {
  if (!currentPiece) return
  
  // 保存当前方块的位置
  const originalY = currentPiece.y
  
  // 找到最低可能的位置
  while (!collision()) {
    currentPiece.y++
  }
  currentPiece.y--
  
  // 绘制阴影
  ctx.fillStyle = 'rgba(128, 128, 128, 0.3)' // 半透明灰色
  currentPiece.shape.forEach((row, y) => {
    row.forEach((value, x) => {
      if (value) {
        const drawX = (currentPiece.x + x) * 32
        const drawY = (currentPiece.y + y) * 32
        ctx.fillRect(drawX, drawY, 31, 31)
      }
    })
  })
  
  // 恢复方块原始位置
  currentPiece.y = originalY
}

// 添加绘制当前方块的函数
const drawCurrentPiece = () => {
  if (!currentPiece) return
  
  ctx.fillStyle = currentPiece.color
  currentPiece.shape.forEach((row, y) => {
    row.forEach((value, x) => {
      if (value) {
        const drawX = (currentPiece.x + x) * 32
        const drawY = (currentPiece.y + y) * 32
        ctx.fillRect(drawX, drawY, 31, 31)
      }
    })
  })
}

// 添加绘制下一个方块的函数
const drawNextPiece = () => {
  if (!nextPiece) return
  
  // 计算居中位置
  const blockSize = 25 // 预览区域的方块大小
  const offsetX = (nextCanvas.value.width - nextPiece.shape[0].length * blockSize) / 2
  const offsetY = (nextCanvas.value.height - nextPiece.shape.length * blockSize) / 2
  
  nextCtx.fillStyle = nextPiece.color
  nextPiece.shape.forEach((row, y) => {
    row.forEach((value, x) => {
      if (value) {
        const drawX = offsetX + x * blockSize
        const drawY = offsetY + y * blockSize
        nextCtx.fillRect(drawX, drawY, blockSize - 1, blockSize - 1)
      }
    })
  })
}

// 移动控制函数
const moveLeft = () => {
  if (!isPlaying.value) return
  currentPiece.x--
  if (collision()) currentPiece.x++
}

const moveRight = () => {
  if (!isPlaying.value) return
  currentPiece.x++
  if (collision()) currentPiece.x--
}

const moveDown = () => {
  if (!isPlaying.value || !currentPiece) return
  
  currentPiece.y++
  if (collision()) {
    currentPiece.y--
    mergePiece()
    currentPiece = nextPiece
    nextPiece = createNewPiece()
    
    // 检查新方块是否可以放置
    if (collision()) {
      // 游戏结束
      isPlaying.value = false
      clearInterval(gameLoop)
      ElMessage.info('游戏结束！')
    }
    
    // 重新绘制
    draw()
  }
}

const rotate = () => {
  if (!isPlaying.value || !currentPiece) return
  
  const matrix = currentPiece.shape
  const N = matrix.length
  const M = matrix[0].length
  
  // 创建新矩阵
  const rotated = Array(M).fill().map(() => Array(N).fill(0))
  
  // 执行旋转
  for (let y = 0; y < N; y++) {
    for (let x = 0; x < M; x++) {
      rotated[x][N - 1 - y] = matrix[y][x]
    }
  }
  
  // 保存原始状态
  const previousShape = currentPiece.shape
  const previousX = currentPiece.x
  const previousY = currentPiece.y
  
  // 尝试旋转
  currentPiece.shape = rotated
  
  // 定义可能的位置调整
  const kicks = [
    { x: 0, y: 0 },   // 原位置
    { x: -1, y: 0 },  // 左移1格
    { x: 1, y: 0 },   // 右移1格
    { x: -2, y: 0 },  // 左移2格
    { x: 2, y: 0 },   // 右移2格
    { x: 0, y: -1 },  // 上移1格
    { x: -1, y: -1 }, // 左上
    { x: 1, y: -1 }   // 右上
  ]
  
  // 尝试所有可能的位置调整
  let validKickFound = false
  for (const kick of kicks) {
    currentPiece.x = previousX + kick.x
    currentPiece.y = previousY + kick.y
    
    if (!collision()) {
      validKickFound = true
      break
    }
  }
  
  // 如果所有调整都失败，恢复原始状态
  if (!validKickFound) {
    currentPiece.shape = previousShape
    currentPiece.x = previousX
    currentPiece.y = previousY
  }
  
  // 确保方块不会超出右边界
  const maxX = 10 - currentPiece.shape[0].length
  if (currentPiece.x > maxX) {
    currentPiece.x = maxX
  }
  
  // 确保方块不会超出左边界
  if (currentPiece.x < 0) {
    currentPiece.x = 0
  }
  
  // 立即重新渲染
  draw()
}

const handleKeyPress = (event) => {
  // 阻止方向键的默认滚动行为
  if ([37, 38, 39, 40].includes(event.keyCode)) {
    event.preventDefault()
  }
  
  // 暂停键 (P)
  if (event.keyCode === 80) {
    toggleGame()
    return
  }
  
  // 重置键 (R)
  if (event.keyCode === 82) {
    resetGame()
    isPlaying.value = false
    return
  }
  
  if (!isPlaying.value) return
  
  switch(event.keyCode) {
    case 37: moveLeft(); break  // 左箭头
    case 39: moveRight(); break // 右箭头
    case 40: moveDown(); break  // 下箭头
    case 38: rotate(); break    // 上箭头
  }
}

// 添加碰撞检测函数
const collision = () => {
  if (!currentPiece) return true
  const shape = currentPiece.shape
  const height = shape.length
  const width = shape[0].length
  
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      if (shape[y][x]) {
        const newX = currentPiece.x + x
        const newY = currentPiece.y + y
        
        // 检查边界和碰撞
        if (
          newX < 0 || 
          newX >= 10 || 
          newY >= 20 ||
          newY < 0 || // 添加顶部边界检查
          (newY >= 0 && board[newY] && board[newY][newX])
        ) {
          return true
        }
      }
    }
  }
  return false
}

// 修改方块合并函数
const mergePiece = () => {
  if (!currentPiece) return
  const shape = currentPiece.shape
  
  // 直接使用当前方块的颜色，而不是通过形状查找索引
  for (let y = 0; y < shape.length; y++) {
    for (let x = 0; x < shape[y].length; x++) {
      if (shape[y][x]) {
        const newY = currentPiece.y + y
        const newX = currentPiece.x + x
        if (newY >= 0) {
          // 存储颜色索引而不是形状索引
          const colorIndex = COLORS.indexOf(currentPiece.color) + 1
          board[newY][newX] = colorIndex
        }
      }
    }
  }
  checkLines()
}

// 修改等级提升逻辑
const checkLines = () => {
  let linesCleared = 0
  for (let y = board.length - 1; y >= 0; y--) {
    if (board[y].every(cell => cell !== 0)) {
      // 在消除行之前创建粒子效果
      board[y].forEach((cell, x) => {
        if (cell !== 0) {
          createParticles(x * 32 + 16, y * 32 + 16, COLORS[cell - 1])
        }
      })
      
      board.splice(y, 1)
      board.unshift(Array(10).fill(0))
      linesCleared++
      y++
    }
  }
  
  if (linesCleared > 0) {
    score.value += linesCleared * 100 * level.value
    if (score.value > level.value * 1000) {
      level.value++
    }
  }
}

const selectGame = (game) => {
  currentGame.value = game
  showGameMenu.value = false
  
  if (game === 'rpg') {
    router.push('/rpg-game')
  } else if (game === 'tetris') {
    // 选择俄罗斯方块时初始化游戏
    init()
  }
}

onMounted(() => {
  // 不要在这里直接调用 init
  // 等待用户选择游戏后再初始化
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyPress)
  cancelAnimationFrame(gameLoop)
})
</script>

<style scoped>
.tetris-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #1a1a1a 0%, #2a2a2a 100%);
  min-height: 100vh;
  color: #fff;
}

/* 优化游戏菜单样式 */
.game-menu {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #1a1a1a 0%, #2a2a2a 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.menu-content {
  text-align: center;
  padding: 2rem;
}

.menu-content h2 {
  color: #fff;
  font-size: 2.5em;
  margin-bottom: 2rem;
  text-shadow: 0 0 10px rgba(255, 95, 22, 0.5);
}

.game-list {
  display: flex;
  gap: 2rem;
  flex-wrap: wrap;
  justify-content: center;
  max-width: 800px;
}

.game-item {
  width: 220px;
  height: 220px;
  background: rgba(255, 255, 255, 0.05);
  border: 2px solid rgba(255, 95, 22, 0.3);
  border-radius: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 1.5rem;
}

.game-item:hover {
  background: rgba(255, 95, 22, 0.1);
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(255, 95, 22, 0.2);
}

.game-icon {
  font-size: 3.5em;
  margin-bottom: 1rem;
}

.game-name {
  color: #fff;
  font-size: 1.4em;
  font-weight: bold;
  margin-bottom: 0.5rem;
}

.game-desc {
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.9em;
}

/* 优化游戏界面样式 */
.game-header {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 1rem 2rem;
  margin-bottom: 2rem;
  width: 100%;
  max-width: 500px;
}

.score-board {
  display: flex;
  gap: 2rem;
}

.score, .level {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.label {
  font-size: 0.9em;
  color: rgba(255, 255, 255, 0.6);
  margin-bottom: 0.3rem;
}

.value {
  font-size: 1.8em;
  font-weight: bold;
  color: #ff5f16;
}

.controls {
  display: flex;
  gap: 1rem;
  margin-top: 1rem;
}

.control-btn {
  padding: 0.8rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
}

.control-btn.primary {
  background: #ff5f16;
}

.control-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 3px 10px rgba(255, 95, 22, 0.2);
}

.game-area {
  display: flex;
  gap: 2rem;
  background: rgba(255, 255, 255, 0.05);
  padding: 2rem;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.game-main {
  flex: none;
}

.game-sidebar {
  flex: none;
}

.next-piece {
  background: rgba(0, 0, 0, 0.2);
  padding: 1rem;
  border-radius: 10px;
  text-align: center;
}

.next-piece h3 {
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 1rem;
  font-size: 1.1em;
}

canvas {
  border: 2px solid rgba(255, 95, 22, 0.3);
  border-radius: 10px;
  background: rgba(0, 0, 0, 0.3);
}

/* 优化移动端控制按钮 */
.mobile-controls {
  margin-top: 2rem;
  padding: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
}

.mobile-controls button {
  padding: 1.2rem;
  border: none;
  border-radius: 10px;
  background: rgba(255, 95, 22, 0.8);
  color: white;
  font-size: 1.4em;
  transition: all 0.2s;
}

.mobile-controls button:active {
  transform: scale(0.95);
  background: #ff5f16;
}

@media (max-width: 768px) {
  .game-item {
    width: 160px;
    height: 160px;
  }
  
  .game-header {
    padding: 1rem;
  }
  
  .value {
    font-size: 1.5em;
  }
  
  .game-area {
    flex-direction: column;
    align-items: center;
    gap: 1rem;
  }
  
  .game-sidebar {
    width: 100%;
  }
}

.key-hints {
  margin-top: 1rem;
  font-size: 0.9em;
  color: rgba(255, 255, 255, 0.6);
  display: flex;
  gap: 1rem;
  justify-content: center;
  flex-wrap: wrap;
}

.key-hints span {
  background: rgba(255, 255, 255, 0.1);
  padding: 0.3rem 0.8rem;
  border-radius: 4px;
}
</style> 